import { USER_INFO } from '../../services/localstorage/cache.service.namespace';
import { CacheService } from '../../services/localstorage/cache.service';
import { LoginApiService } from '../../services/login/login-api.service';
import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  constructor(private fb: FormBuilder, private loginApi: LoginApiService, private storage: CacheService) { }

  validateForm: FormGroup;
  username: String;
  password: String;

  submitForm(): void {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    this.loginApi.login(this.username, this.password).subscribe(response => {
      if (response.success) {
          this.storage.set(USER_INFO, response.data);

          console.log(this.storage.get(USER_INFO));
      }
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true]
    });
  }
}
